<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card class="box-card">

      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="paramsInfo.query"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsers"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button
            type="primary"
            @click="addDialogUserVisible = true"
          >添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="index">
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
        >
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
        >
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色"
        >
        </el-table-column>
        <el-table-column
          prop="mg_state"
          label="状态"
          width="70"
        >
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <!-- {{ scope.row.mg_state }} -->

            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="UserStatusChange(scope.row)"
            >
            </el-switch>

          </template>

        </el-table-column>
        <el-table-column
          label="操作"
          width="180"
        >
          <template slot-scope="scope">
            <!-- {{ scope.row.mg_state }} -->
            <!-- 编辑 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editDialogShow(scope.row)"
            ></el-button>

            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>

            <!-- 分配权限 -->
            <el-tooltip
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="RoleDialogShow(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>

        </el-table-column>

      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paramsInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="paramsInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加用户 弹出框  -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogUserVisible"
        width="40%"
        @close="addDialogUserClose"
      >
        <!-- 内容 B -->
        <el-form
          :model="addUserForm"
          :rules="addUserFormRules"
          ref="addUserFormRef"
          label-width="70px"
        >
          <el-form-item
            label="用户名"
            prop="username"
          >
            <el-input
              v-model="addUserForm.username"
              clearable
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="密码"
            prop="password"
          >
            <el-input
              type="password"
              v-model="addUserForm.password"
              clearable
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="邮箱"
            prop="email"
          >
            <el-input
              v-model="addUserForm.email"
              clearable
              placeholder="请输入邮箱"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="电话"
            prop="mobile"
          >
            <el-input
              v-model="addUserForm.mobile"
              clearable
              placeholder="请输入电话号"
            ></el-input>
          </el-form-item>

        </el-form>
        <!-- 内容 E -->

        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="addDialogUserVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="addUser"
          >确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑用户 弹出框 -->
      <el-dialog
        title="编辑用户"
        :visible.sync="editDialogUserVisible"
        width="40%"
        @close="editDialogUserClose"
      >
        <!-- 内容 B -->
        <el-form
          :model="editUserForm"
          :rules="editUserFormRules"
          ref="editUserFormRef"
          label-width="70px"
        >
          <el-form-item
            label="用户id"
            prop="id"
          >
            <el-input
              v-model="editUserForm.id"
              disabled
            ></el-input>
          </el-form-item>

          <el-form-item
            label="邮箱"
            prop="email"
          >
            <el-input
              v-model="editUserForm.email"
              clearable
            ></el-input>
          </el-form-item>

          <el-form-item
            label="电话"
            prop="mobile"
          >
            <el-input
              v-model="editUserForm.mobile"
              clearable
            ></el-input>
          </el-form-item>

        </el-form>
        <!-- 内容 E -->

        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="editDialogUserClose">取 消</el-button>
          <el-button
            type="primary"
            @click="editUser"
          >确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配权限 弹出框 -->
      <el-dialog
        title="分配用户权限"
        :visible.sync="RoleDialogVisible"
        width="30%"
        @close="RoleDialogHandleClose()"
      >
        <div>
          <p>当前的用户：{{ RoleSetUserInfo.username }} </p>
          <p>当前的角色：{{RoleSetUserInfo.role_name}}</p>
          <p>
            分配新角色：
            <el-select
              v-model="RolesId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in RoleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="RoleDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="settingUser"
          >确 定</el-button>
        </span>
      </el-dialog>

    </el-card>

  </div>
</template>

<script>
export default {
  data() {
    // 邮箱验证
    var checkEmail = (rule, value, callback) => {
      // 邮箱正则
      const regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        // 合法邮箱
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 手机号验证
    var checkMoilbe = (rule, value, callback) => {
      const regMoilbe = /^1[3456789]\d{9}$/
      if (regMoilbe.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    return {
      token: '',
      total: 0,
      paramsInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      tableData: [],
      // 添加用户 visible
      addDialogUserVisible: false,
      // 添加用户 数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户 校验
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在3到10个字符之间', trigger: 'blur' }
        ],

        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 8, message: '密码的长度在6到8个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号', trigger: 'blur' },
          { validator: checkMoilbe, trigger: 'blur' }
        ]
      },
      // 编辑用户 visible
      editDialogUserVisible: false,
      // 编辑用户数据
      editUserForm: {
        id: '',
        email: '',
        mobile: ''
      },
      // 编辑用户验证
      editUserFormRules: {
        id: [{ required: true, message: '请输入id', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号', trigger: 'blur' },
          { validator: checkMoilbe, trigger: 'blur' }
        ]
      },
      // 分配权限
      RoleDialogVisible: false,
      RoleSetUserInfo: [], // 
      RoleList: [], // 所有权限列表
      RolesId: ''
    }
  },
  created() {
    this.token = window.sessionStorage.getItem('token')
    this.getUsers()
    this.getRolesList()
  },
  methods: {
    // 获取用户列表
    async getUsers() {
      const { data: res } = await this.$axios.get('users', {
        params: this.paramsInfo,
        headers: { 'Authorization': this.token }
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.total = res.data.total
      // console.log(this.total)
      this.tableData = res.data.users
      // console.log(res)
    },
    // 监听 分页 页数
    handleSizeChange(newSize) {
      console.log(newSize)
      this.paramsInfo.pagesize = newSize
      this.getUsers()
    },
    // 监听 页码
    handleCurrentChange(newPageNum) {
      console.log(newPageNum)
      this.paramsInfo.pagenum = newPageNum
      this.getUsers()
    },
    // 更改用户状态
    async UserStatusChange(userinfo) {
      // console.log(userInfo)
      // console.log(userInfo.mg_state)
      const { data: res } = await this.$axios.put(`users/${userinfo.id}/state/${userinfo.mg_state}`, {}, {
        headers: { 'Authorization': this.token }
      })

      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功！')
      // console.log(res)
    },
    // 监听 添加用户弹窗 关闭
    addDialogUserClose() {
      this.$refs.addUserFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addUserFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        const { data: res } = await this.$axios.post('users', this.addUserForm, {
          headers: {
            'Authorization': this.token
          }
        })
        console.log(res)

        if (res.meta.status !== 201) {
          this.$message.error(res.meta.msg)
          return
        }
        // 关闭添加用户窗口
        this.addDialogUserVisible = false
        this.$message.success(res.meta.msg)
        // 重新调用
        this.getUsers()
      })
    },
    // 监听编辑用户 弹出框 关闭
    editDialogUserClose() {
      // console.log('关闭啦')
      this.editDialogUserVisible = false
      this.$refs.editUserFormRef.resetFields()
    },
    // 点击编辑用户 按钮
    async editDialogShow(data) {
      // console.log(data)
      this.editDialogUserVisible = true

      let editUserForm = {
        id: data.id,
        email: data.email,
        mobile: data.mobile
      }
      this.editUserForm = editUserForm
    },
    // 编辑用户 提交
    editUser() {
      // console.log(this.editUserForm)
      this.$refs.editUserFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$axios.put(`users/${this.editUserForm.id}`, {
          'email': this.editUserForm.email,
          'mobile': this.editUserForm.mobile
        }, {
          headers: {
            'Authorization': this.token
          }
        })

        console.log(res)

        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          return
        }

        this.$message.success(res.meta.msg)
        this.editDialogUserVisible = false
        // 重新调用
        this.getUsers()
      })
    },
    // 删除用户  
    async deleteUser(id) {
      console.log(id)
      let confirm = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // console.log(confirm)
      if (confirm === 'cancel') {
        this.$message.info('已取消删除')
        return
      }

      let { data: res } = await this.$axios.delete('users/' + id, {
        headers: {
          'Authorization': this.token
        }
      })

      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        return
      }
      this.$message.success(res.meta.msg)
      console.log(res)
      // 重新调用
      this.getUsers()
    },
    // 获取所有 角色列表
    async getRolesList() {
      const { data: res } = await this.$axios.get('roles', {
        headers: {
          'Authorization': this.token
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.RoleList = res.data
    },
    // 显示分配权限弹窗
    RoleDialogShow(data) {
      this.RoleDialogVisible = true
      this.RoleSetUserInfo = data
    },
    // 分配用户权限
    async settingUser() {
      console.log(this.RoleSetUserInfo.id)
      let { data: res } = await this.$axios.put(`users/${this.RoleSetUserInfo.id}/role`, {
        rid: this.RolesId
      }, {
        headers: {
          'Authorization': this.token
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.getUsers()
      this.RoleDialogVisible = false
      // console.log(res)
    },
    // 关闭分配权限弹窗
    RoleDialogHandleClose() {
      this.RoleSetUserInfo = {}
      this.RolesId = ''
    }
  }

}
</script>

<style lang="scss" scoped>
.container {
  .el-table .warning-row {
    background: oldlace
  }

  .el-table .success-row {
    background: #f0f9eb
  }
}
</style>